/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.group4.highschoolportal.service;

import java.util.Properties;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Andreas
 */
@ManagedBean(name = "mailer")
@ApplicationScoped
public class MailerBean {

    //config to mail
    private final String host = "smtp.gmail.com";
    private final int port = 587;
    private final String username = "hswebapps@gmail.com";
    private final String password = "kalle4545";

    /** Creates a new instance of MailerBean */
    public MailerBean() {
    }

    /**
     * Sends mail
     */
    public void sendMail(String to, String subject, String mailMessage) {

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", username);
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props);

        try {

            Message message = new MimeMessage(session);
            message.setSubject(subject);
            message.setFrom(InternetAddress.parse(username)[0]);
            message.setText(mailMessage);

            Transport transport = session.getTransport("smtp");
            transport.connect(host, username, password);
            
            transport.sendMessage(message, InternetAddress.parse(to));

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }
}
